# employment/router.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional
from ..database import get_db
from . import schemas, crud, models

router = APIRouter(prefix="/employment", tags=["employment"])

@router.get("/", response_model=List[schemas.Employment], summary="获取所有就业记录", description="获取所有学生就业记录，支持分页")
def read_all_employment(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    employment_records = db.query(models.Employment).offset(skip).limit(limit).all()
    # 转换日期字段为字符串
    for record in employment_records:
        if hasattr(record, 'job_search_start') and record.job_search_start:
            record.job_search_start = str(record.job_search_start)
        if hasattr(record, 'offer_date') and record.offer_date:
            record.offer_date = str(record.offer_date)
    return employment_records

@router.post("/", response_model=schemas.Employment, summary="添加就业记录", description="创建新的学生就业记录")
def create_employment(employment: schemas.EmploymentCreate, db: Session = Depends(get_db)):
    return crud.crud_employment.create(db, employment)

@router.get("/student/{student_id}", response_model=List[schemas.Employment], summary="获取学生就业记录", description="根据学生ID获取就业记录")
def read_employment_by_student(student_id: str, db: Session = Depends(get_db)):
    return crud.crud_employment.get_by_student(db, student_id)

@router.get("/class/{class_name}", response_model=List[schemas.Employment], summary="获取班级就业记录", description="根据班级名称获取就业记录")
def read_employment_by_class(class_name: str, db: Session = Depends(get_db)):
    return crud.crud_employment.get_by_class(db, class_name)

@router.get("/filter/", response_model=List[schemas.Employment], summary="筛选就业记录", description="根据学生ID、公司名称、薪资范围筛选就业记录")
def filter_employment(
    student_id: Optional[str] = None,
    company_name: Optional[str] = None,
    min_salary: Optional[int] = None,
    max_salary: Optional[int] = None,
    db: Session = Depends(get_db)
):
    return crud.crud_employment.get_by_filter(db, student_id, company_name, min_salary, max_salary)

@router.put("/{student_id}", response_model=schemas.Employment, summary="更新就业记录", description="根据学生ID更新就业记录")
def update_employment(student_id: str, employment: schemas.EmploymentUpdate, db: Session = Depends(get_db)):
    db_employment = crud.crud_employment.update(db, student_id, employment)
    if db_employment is None:
        raise HTTPException(status_code=404, detail="Employment record not found")
    return db_employment

@router.delete("/{student_id}", summary="删除就业记录", description="根据学生ID删除就业记录")
def delete_employment(student_id: str, db: Session = Depends(get_db)):
    success = crud.crud_employment.delete(db, student_id)
    if not success:
        raise HTTPException(status_code=404, detail="Employment record not found")
    return {"message": "Employment record deleted successfully"}